Date.prototype.format = function(fmt){
  var o = {
    "M+" : this.getMonth()+1,                 //月份
    "d+" : this.getDate(),                    //日
    "h+" : this.getHours(),                   //小时
    "m+" : this.getMinutes(),                 //分
    "s+" : this.getSeconds(),                 //秒
    "q+" : Math.floor((this.getMonth()+3)/3), //季度
    "S"  : this.getMilliseconds()             //毫秒
  };

  if(/(y+)/.test(fmt)){
    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
  }
        
  for(var k in o){
    if(new RegExp("("+ k +")").test(fmt)){
      fmt = fmt.replace(
        RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));  
    }       
  }

  return fmt;
};

$('#dateselect-input').datepicker({
	format: 'yyyymmdd',
	autoclose: true,
	todayBtn: 'linked',
	todayHighlight: true,
	language: 'zh-CN',
	beforeShowDay: function(date) {
        $.ajaxSettings.async = false;
        window.dayBookCount = 0;
        $.get("/countbydate", {"date": date.format("yyyyMMdd")}, function(ret) {
            window.dayBookCount = ret.count;
        });
        $.ajaxSettings.async = true;
        if (window.dayBookCount > 0) {
            return "date-marked";
        }
	}
});

$('#dateselect-input').on('change', function(event) {
	$('#booktable').bootstrapTable('refresh');
});

function addbook() {
    var bootstrapValidator = $("#booksubmitform").data('bootstrapValidator');
    bootstrapValidator.validate();
    if (bootstrapValidator.isValid()) {
       var data = {
            bookname: $('#booksubmitforme-input-bookname').val(),
            bookcategory: $('#booksubmitforme-select-bookcategory').val(),
            dateselected: $('#dateselect-input').val()
       };
       $.post("/add", data, function(result) {
            if (result.ok == false) {
                $('#request-result-dialog-content')[0].innerHTML="出错了，请联系网站管理员";
                $('#request-result-dialog').modal('show');
            }
            bootstrapValidator.resetForm();
            $('#booktable').bootstrapTable('refresh');
       });
    }
}

function setdeletebookdata(bookid) {
	$('#bookdelete-modal-dialog-bookid').val(bookid);
	$('#bookdelete-confirm-dialog-content')[0].innerHTML = "<p style='color:red;'>确认删除?</p>";
};

function deletebookbyid() {
    var bookid = $('#bookdelete-modal-dialog-bookid').val();
    var data = {
        bookid: bookid
    };
    $.post("/del", data, function(result) {
        if (result.ok == false) {
            $('#request-result-dialog-content')[0].innerHTML="出错了，请联系网站管理员";
            $('#request-result-dialog').modal('show');
        }
        $('#booktable').bootstrapTable('refresh');
    });
}

$('#booktable').bootstrapTable({
    url: '/books',
    method: 'get',
    cache: false, 
    queryParams :queryParams,
    locale: "zh-CN",
    columns: [{
        field: 'name',
        title: '书名',
        align: 'center'
    }, {
        field: 'category',
        title: '种类',
        align: 'center',
        formatter: function(value, row, index) {
            if (value == "Chinese") {
                return "中文";
            } else if (value == "English") {
                return "英文";
            } else if (value == "Poem") {
                return "诗词";
            } else {
                return "其他";
            }
        }
    } , {
        field: '',
        title: '操作',
        align: 'center',
        formatter: function (value, row, index) {
        	button_string = "<button class=\"btn btn-xs btn-danger\" data-target=\"#bookdelete-confirm-dialog\" data-toggle=\"modal\""
        		+ "onclick=setdeletebookdata(\"" + row.id + "\")" + " >删除</button>";
        	return button_string;
        }
    }]
});

function queryParams(params) {
     var temp = {
		 dateselected: $('#dateselect-input').val()
     };
     return temp;
 }

$('#booksubmitform').bootstrapValidator({
    message: '该值不合法',
    live: 'enabled',
    feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
        bookname: {
            validators: {
                notEmpty: {
                    message: '不能为空'
                }
            }
        }
    }
});

$('#booksubmitform').on('keydown', function(event) {
    if (event.which == '13') {
        event.preventDefault();
    }
});

$('#booksubmitforme-input-bookname').on("focus", function() {
    $('#booksubmitforme-input-bookname').get(0).select();
});